#!/usr/bin/perl -w

@P=qw(/usr/bin /usr/sbin /usr/local/bin /bin /sbin);

$VIRSH=undef;
for (@P) {
	if(-f "$_/virsh" && -x _) {
		$VIRSH="$_/virsh";last;
	}
}

if(!defined($VIRSH)) {
	print STDERR "virsh executable not found.\n";
	exit(1);
}

$machine=$ARGV[0];

# Check to see if the machine exists and about if not.
# If does exist, might already be shutdown.

$r=`$VIRSH list --all 2>&1`;
if($?>>8) {
	print STDERR "ERROR: Failed to list libvirt virtual machines.\n";
	exit(2);
}

$found=0; $state="";
@L=split(/\n/,$r);
for my $cline (@L[2 .. $#L]) {
	my $x=$cline;
	$x =~ s/^\s+//;
	my @S=split(/\s+/,$x);
	if($S[1] eq $machine) {
		$found=1; $state=$S[2];
		last;
	}
}

if(! $found) {
	print STDERR "ERROR: libvirt not able to find machine $machine.\n";
	exit(2);
}

if($state =~ /^shut/) {
	exit(1);
}

exit(0); # assume running it not down

